/*
 * Created on Nov 20, 2003
 */
 
package com.unash.asn;

/**
 * @author Ashwini Gokhale
 */

import com.unash.util.AsnUtil;
import com.unash.util.Consts;

public class AsnOctetString implements Consts{
	private final byte[] value;
	
	/**
	 * @param value bytearray representation of the bitstring.
	 * @throws IllegalArgumentException
	 */
	public AsnOctetString(byte[] value) 
		   throws IllegalArgumentException 
	{
		if ((null == value) || (ZERO >= value.length))
			throw new IllegalArgumentException();
		this.value = value;
	}//AsnOctetString(byte[] value)


	public boolean equals(Object obj) {
		if (!(obj instanceof AsnOctetString))
			return false;

		AsnOctetString objAsnOctetString = (AsnOctetString) obj;
		if (getValue().length != objAsnOctetString.getValue().length)
			return false;

		for (int i = ZERO; i < getValue().length; i++) {
			if (getValue()[i] != objAsnOctetString.getValue()[i])
				return false;
		}//for
		return true;
	}//equals(Object obj)


	public int hashCode() {
		int result = 17;
		for(int i=ZERO;i<getValue().length;i++){
			result = 37 * result + getValue()[i]; 
		}//for
	 	return result;
	}//hashCode()


	/**
	 * 
	 * @param index ranging from 1 to size of bitString.
	 * @return true if bit = 1
	 * @throws IllegalArgumentException
	 * This function checks whether the specified bit is set to 1.
	 */
	public boolean isBitSet(int index)
		throws IllegalArgumentException
	{
		if((ZERO >= index) || (getValue().length * BYTE_SIZE) < index)
			throw new IllegalArgumentException();
	
		//get the index in the byte array
		int byteIndex = (index - ONE)/BYTE_SIZE;
	
		//find the distance for shifting value to right
		int noBitRShift = (byteIndex + ONE) * BYTE_SIZE - index;
	
		//RightShift	
		int rShiftValue = getValue()[byteIndex] >> noBitRShift;
		
		return((rShiftValue & MASK) == ONE);	
	}//isBitSet(int index)
	
	
	public String toString(){
		StringBuffer octetString = new StringBuffer();
		for(int i=ZERO; i < getValue().length; i++){
			for(int j=ONE; j <= BYTE_SIZE; j++){
				if(AsnUtil.isBitSet(getValue()[i],j))
					octetString.append(STR_ONE);
				else
					octetString.append(STR_ZERO);
			}//for(int j=1;j<=BYTE_SIZE;j++)
		}//for(int i=ZERO;i<value.length;i++)
		return octetString.toString();
	}//toString()


	public byte[] getValue() {
		return value;
	}	
}//AsnOctetString